package cn.topcode.unicorn.utils;

import java.io.*;

public class IOUtil {
    
    private IOUtil() {}

    /**
     * 将输入流转换为字符串，默认编码为UTF-8
     * @param in
     * @return
     */
    public static String toString(InputStream in) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        try {
            while ((i = in.read()) != -1) {
                baos.write(i);
            }
        } catch (IOException e) {
            return null;
        }
        try {
            return baos.toString("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将输入流转换为字节数组
     * @param in
     * @return
     */
    public static byte[] toBytes(InputStream in) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i = -1;
        try {
            while ((i = in.read()) != -1) {
                baos.write(i);
            }
        } catch (IOException e) {
            return null;
        }
        return baos.toByteArray();
    }

    public static void copyTo(FileInputStream chunkFileIn, FileOutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len = chunkFileIn.read(buffer)) != -1) {
            out.write(buffer,0,len);
        }
    }
}
